package com.aliyun.messagemgt.application.service.Impl;

import com.aliyun.messagemgt.application.service.FileUpload;
import com.aliyun.messagemgt.application.service.media.BloomFilter;
import com.aliyun.messagemgt.util.OSSUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileUploadImpl implements FileUpload {

	private static final Logger logger = LoggerFactory.getLogger(FileUploadImpl.class);

    @Autowired
    private BloomFilter bloomFilter;

    @Override
    public String pictureToUrl(MultipartFile file) {
        InputStream pictureStream = null;
        try {
            pictureStream = file.getInputStream();
        } catch (IOException e) {
            logger.error("图片流获取失败", e);
            return null;
        }

        String transferUrl = null;
        String uuid = UUID.randomUUID().toString();
        try {
            transferUrl = OSSUtil.uploadInputStream(pictureStream, "png", uuid);
        } catch (IOException e) {
            logger.error("图片上传oss失败", e);
            return null;
        }
        // 1. 布隆过滤器
        // 2. 存到映射表
      /*  UrlMgt urlMgt = new UrlMgt().setOriginUrl(transferUrl).setOriginUrlHash(transferUrl.hashCode())
                .setTransferUrl(transferUrl).setUrlCode(uuid);
        List<UrlMgt> urlMgtList = Arrays.asList(urlMgt);*/
        // urlMgtService.batchUrlMgtInsert(urlMgtList);
        return uuid;
    }

    @Override
    public String pictureToUrl2(MultipartFile file) {
        InputStream pictureStream = null;
        try {
            pictureStream = file.getInputStream();
        } catch (IOException e) {
            logger.error("图片流获取失败", e);
        }

        String transferUrl = null;
        String uuid = UUID.randomUUID().toString();
        try {
            transferUrl = OSSUtil.uploadInputStream(pictureStream, "png", uuid);
        } catch (IOException e) {
            logger.error("图片上传oss失败", e);
        }
        if(null != transferUrl){
            // 1. 布隆过滤器
            bloomFilter.containAndAdd(transferUrl);
            // 2. 存到映射表
            /*UrlMgt urlMgt = new UrlMgt().setOriginUrl(transferUrl).setOriginUrlHash(transferUrl.hashCode())
                    .setTransferUrl(transferUrl);*/
            // urlMgtService.batchUrlMgtInsert(Arrays.asList(urlMgt));
        }
        return transferUrl;
    }

}
